package day200.LC142;

public class Main {
    public static void main(String[] args) {

    }
}


//Definition for singly-linked list.
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }
}

class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }
        ListNode fast=head;
        ListNode slow=head;
        while (fast != null) {
            fast= fast.next;
            if (fast==null){
                return null;
            }
            fast= fast.next;
            slow=slow.next;
            if (fast == slow) {
                break;
            }
        }
        if (fast == null) {
            return null;
        }
        //相遇、有环
        ListNode temp=head;
        while (temp != slow) {
            temp=temp.next;
            slow=slow.next;
        }
        return slow;
    }
}
